import toolMgr from '@/biz/base/tool.js'
import dt from '@dt/dt'
import houseOpt from '@/biz/option/house.js'
import productOpt from '@/biz/option/product.js'
import ruleOpt from '@/biz/option/rule.js'
import uploadOpt from '@/biz/option/upload.js'
let _this = null

function baseAgent() {
  function rules() {
    let arr = [
      ruleOpt.required(text(), 'number'),
      ruleOpt.positiveNumber(),
    ]
    if (_this.info.baseAgentType == '1') {
      arr.push(ruleOpt.percent())
      arr.push(ruleOpt.check('代理费率保留四位小数', (val) => {
        let reg = /^\d+(\.\d{1,4}){0,1}$/
        return !reg.test(val) ? true : false
      }, 'blur'))
    } else {
      arr.push(ruleOpt.twoDecimal())
    }
    return arr
  }

  function text() {
    return _this.info.baseAgentType == '2' ? '请输入固定金额' : '请输入代理费率'
  }

  function unit() {
    return _this.info.baseAgentType == '2' ? '元' : '%'
  }

  function group() {
    return [{
      key: 'baseAgentType',
      col: 6,
      select: {
        options: dt.dictInfo().BaseAgentTypeEnum,
      },
      change: () => {
        opt.group = group()
        opt.rules = rules()
      }
    }, {
      key: 'baseAgentCost',
      col: 12,
      placeholder: text(),
      input: {
        type: 'number'
      }
    }, {
      placeholder: unit(),
      col: 6,
      text: {}
    }]
  }
  let opt = {
    title: '基础代理费',
    key: 'baseAgentCost',
    group: group(),
    rules: rules()
  }

  return opt
}

function contract() {
  return {
    title: '签约比例',
    key: 'contractPer',
    group: [{
      key: 'contractPer',
      col: 12,
      placeholder: '请输入签约比例',
      input: {
        type: 'number'
      }
    }, {
      placeholder: '%',
      col: 2,
      text: {}
    }, {
      placeholder: '(全款默认按100%计算总销)',
      col: 10,
      text: {}
    }],
    rules: [{
        type: 'number',
        required: true,
        message: '请输入签约比例',
        trigger: 'blur'
      },
      ruleOpt.twoDecimal(),
      ruleOpt.positiveNumber(),
      ruleOpt.percent(),
      // ruleOpt.check('与保证金比例之和不可大于100%', (value) => {
      //   return Number(_this.info.depositPer) + Number(value) >= 100.01
      // })
    ]
  }
}

function cut() {
  return {
    title: '签约扣除保证金',
    key: 'isDeductDeposit',
    radio: {
      options: [{
        key: 1,
        value: '是'
      }, {
        key: 0,
        value: '否'
      }]
    },
    data: {
      from: (info) => {
        return info.isDeductDeposit ? 1 : 0
      },
      to: (v) => {
        return {
          isDeductDeposit: v == 1
        }
      }
    },
    rules: [{
      type: 'boolean',
      required: true,
      message: '请选择签约是否扣除保证金',
      trigger: 'blur'
    }]
  }
}

function deposit() {
  return {
    title: '交房保证金比例',
    key: 'depositPer',
    group: [{
      key: 'depositPer',
      col: 12,
      placeholder: '请输入保证金比例',
      input: {
        type: 'number'
      }
    }, {
      placeholder: '%',
      col: 6,
      text: {}
    }],
    rules: [{
        type: 'number',
        required: true,
        message: '请输入保证金比例',
        trigger: 'blur'
      },
      ruleOpt.twoDecimal(),
      ruleOpt.positiveNumber(),
      ruleOpt.percent(),
      // ruleOpt.check('与签约比例之和不可大于100%', (value) => {
      //   return Number(_this.info.contractPer) + Number(value) >= 100.01
      // })
    ]
  }
}

function accessory(info) {
  let api = toolMgr.unloadFile()
  let files = []
  if (info.accessoryBOList && info.accessoryBOList.length > 0) {
    info.accessoryBOList.forEach(item => {
      if (item) {
        files.push({
          name: item.accessoryName,
          url: item.accessoryUrl
        })
      }
    })
  }
  return {
    title: '代理合同附件',
    key: 'accessoryBOList',
    placeholder: '(最大支持50M文件，若文件过大请压缩或分多个文件)',
    upload: {
      maxSize: 51200,
      title: '附件上传',
      api,
      files,
      multiple: true,
      preview: (file) => {
        toolMgr.downloadFile(file.url, file.name)
      }
    },
    data: {
      to: (v) => {
        let accessoryBOList = v.map(item => {
          return {
            accessoryName: item.name,
            accessoryUrl: item.response ? item.response.data.imageURL : item.url
          }
        })
        return {
          accessoryBOList
        }
      }
    },
    rules: [{
      required: true,
      message: '请上传代理合同附件',
      type: 'array',
      trigger: 'blur'
    }]
  }
}

function productInfo(info) {
  return productOpt.create({
    key: 'productIds',
    multiple: true,
    hid: info.housesId,
    data: {
      from: (info) => {
        if (info.productIds) {
          return info.productIds.split(',')
        }
        return null
      },
      to: (v) => {
        let productIds = ''
        let productNames = ''
        v.forEach((item, idx) => {
          productIds += (item.value + ((idx == v.length - 1) ? '' : ','))
          productNames += (item.label + ((idx == v.length - 1) ? '' : ','))
        })
        return {
          productIds,
          productNames
        }
      }
    }
  })
}

function houseInfo(info) {
  let opt = {
    change: () => {
      info.productIds = null
      _this.update()
    }
  }
  if (info.housesId) {
    opt.options = [{
      key: info.housesId + '-' + info.companyId,
      value: info.housesName + '（' + info.companyName + '）'
    }]
  }
  return houseOpt.create(opt)
}

let validDate = [{
  title: '有效期',
  placeholder: '请选择日期范围',
  key: 'startDate',
  tip: '请注意：结佣订单将根据所选结佣生效方式及有效期进行匹配规则',
  date: {
    type: 'daterange'
  },
  data: {
    from: (info) => {
      if (info.startDate && info.endDate) {
        return [info.startDate, info.endDate]
      }
      return null
    },
    to: (v) => {
      return {
        startDate: v[0],
        endDate: v[1],
      }
    }
  },
  rules: [{
    required: true,
    message: '请选择有效期',
    trigger: 'blur'
  }]
}]

function part1() {
  return [
    houseInfo(_this.info),
    {
      title: '佣金规则名称',
      placeholder: '请输入佣金规则名称',
      key: 'ruleName',
      input: {},
      rules: [{
        required: true,
        message: '请输入佣金规则名称',
        trigger: 'blur'
      }, {
        max: 20,
        message: '最多20个字',
        trigger: 'blur,change'
      }]
    },
    productInfo(_this.info),
    {
      title: '结佣生效方式',
      key: 'validWay',
      radio: {
        options: dt.dictInfo().ValidWayEnum,
      },
      rules: [{
        required: true,
        message: '请选择结佣生效方式',
        trigger: 'blur'
      }]
    },
    validDate,
    {
      title: '结佣参考价',
      key: 'refPrice',
      radio: {
        options: [{
          key: '1',
          value: '总价'
        }]
      },
      rules: [{
        required: true,
        message: '请选择结佣参考价',
        trigger: 'blur'
      }]
    },
    baseAgent()
  ]
}

function part2() {
  return [
    // accessory(_this.info),
    uploadOpt.fileOss({
      title: '代理合同附件',
      key: 'accessoryBOList',
      placeholder: '(最大支持50M文件，若文件过大请压缩或分多个文件)',
      maxlength: 10,
      hideDel: false,
      show: false,
      maxSize: 51200,
      showDel:true,
      multiple: true,
      itemName: 'accessoryName',
      itemUrl: 'accessoryUrl',
      rules: [
        ruleOpt.required('请选择上传代理合同', 'array')
      ]
    }, _this.info),


    {
      title: '备注',
      key: 'remark',
      input: {
        type: 'textarea',
        autosize: {
          minRows: 2
        }
      },
      rules: [
        ruleOpt.max(300)
      ]
    }
  ]
}

function options(vm) {
  _this = vm
  let arr = []

  let p1 = part1()
  let p2 = [deposit(), ...part2()]
  let commission = {
    title: '结佣方式',
    key: 'commissionWay',
    radio: {
      options: dt.dictInfo().CommissionWayEnum,
    },
    change: () => {
      _this.info.depositPer = null
      _this.info.contractPer = null
      arr.splice(0, arr.length)
      arr.push(...p1)
      if (_this.info.commissionWay == 2) {
        arr.push(contract())
        arr.push(cut())
      }
      arr.push(...p2)
    },
    rules: [{
      required: true,
      message: '请选择结佣方式',
      trigger: 'blur'
    }]
  }
  p1.push(commission)

  arr.push(...p1)
  if (_this.info.commissionWay == 2) {
    arr.push(contract())
    arr.push(cut())
  }
  arr.push(...p2)
  return arr
}

export default {
  options
}